# -*- coding: utf-8 -*-
import scrapy
from first.items import GameItem


class GamespiderSpider(scrapy.Spider):
    name = 'gamespider'
    start_urls = ['http://game.pcgames.com.cn/list/f101.html']

    def parse(self, response):
        games = response.css(
            'body > div.wrap > div.inner.dMainnav.mb10\
            > div > span.dMainnav-in-l.fl')
        for ug in games.xpath('a/@href'):
            yield scrapy.Request(ug.extract(), callback=self.parse_games)

    def parse_games(self, response):
        games = response.xpath('//*[@id="ulListPic"]/li/div[2]')
        for game in games:
            gameItem = GameItem()
            gameItem['title'] = game.xpath(
                'div[2]/strong/a/text()').extract_first()
            gameItem['iid'] = game.xpath('div[1]/a/img/@src').extract_first()
            content = dict()
            content['url'] = game.xpath('div[1]/a/@href').extract_first()
            content['rating'] = len(game.xpath('div[2]/div[1]/em'))
            content['poll'] = game.xpath(
                'div[2]/div[2]/span/text()').extract_first()
            content['开发'] = game.xpath('p[1]/span[1]/a/text()').extract_first()
            content['运营'] = game.xpath('p[1]/span[2]/a/text()').extract_first()
            content['平台'] = game.xpath('p[2]/span[1]/a/text()').extract_first()
            content['画面'] = game.xpath('p[2]/span[2]/a/text()').extract_first()
            gameItem['content'] = content
            yield gameItem
        next_page = response.css(
            'body > div.wrap > div.inner.dList > div.layAB >\
            div.modA > div.tbA > div > a.next')

        if next_page is not None and len(next_page) > 0:
            url = next_page.xpath('@href').extract_first()
            yield scrapy.Request(url, callback=self.parse_games)
